package com.proxy;

import com.annotations.rpc.Discovery;
import com.channel.ChannelContent;
import com.config.Config;
import com.constant.PromiseConstant;
import com.message.rpc.RpcRequestMessage;
import com.message.rpc.RpcResponseMessage;
import io.netty.channel.Channel;
import io.netty.util.concurrent.DefaultPromise;
import io.netty.util.concurrent.Promise;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * @author linyu.dai
 * @project rpc
 * @description rpc代理
 * @creat 2022/11/27 21:06:13
 */
@Slf4j
public class JdkInvocationHandle implements InvocationHandler {

    private Class<?> aClass;

    public JdkInvocationHandle(Class<?> aClass){
        this.aClass = aClass;
    }

    /**
     * @Author linyu.dai
     * @Description 拦截方法
     * @Date 2022/11/27 21:09
     * @Param [proxy, method, args]
     * @return java.lang.Object
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        String serviceName = aClass.getAnnotation(Discovery.class).name();
        String serverName = aClass.getAnnotation(Discovery.class).serverName();
        RpcRequestMessage rpcRequestMessage = new RpcRequestMessage(
                UUID.randomUUID().toString(),
                serviceName,
                method.getName(),
                method.getReturnType(),
                method.getParameterTypes(),
                args
        );
        //获取连接的channel
        Channel channel = ChannelContent.getChannel(serverName);
        if(Objects.nonNull(channel)) {
            //指定promise对应异步接收结果的线程
            Promise<Object> response = new DefaultPromise<>(channel.eventLoop());
            //设置promise便于通知
            PromiseConstant.setPromise(rpcRequestMessage.getMessageId(), response);
            //线程提交任务
            Future<Object> submit = Config.getExecutorService().submit(() -> {
                channel.writeAndFlush(rpcRequestMessage);
                try {
                    RpcResponseMessage rpcResponseMessage = (RpcResponseMessage) response.get();
                    if (Objects.nonNull(rpcResponseMessage.getExceptionValue())) {
                        throw rpcResponseMessage.getExceptionValue();
                    }
                    return rpcResponseMessage.getReturnValue();
                } catch (Exception e) {
                    log.error("rpc 调用失败:{}", e.getMessage());
                }
                return null;
            });
            //执行其他任务
            return submit.get(3, TimeUnit.SECONDS);
        }else {
            log.error("{}未启动或者连接失败.....",serviceName);
            return null;
        }
    }

    /**
     * @Author linyu.dai
     * @Description 获取代理对象
     * @Date 2022/11/27 21:09
     * @Param []
     * @return java.lang.Object
     */
    public static Object getProxy(Class<?> aClass){
        return Proxy.newProxyInstance(aClass.getClassLoader(), new Class[]{aClass}, new JdkInvocationHandle(aClass));
    }
}
